<template>
  <div class="app-bg auto">
    <div class="auto" style="background:#108ADD;text-align:center; padding:10px 0px;color:#FFF;font-size: 18px;">
      博能燃气手机抄表
    </div>
      <div class="row app-input">
        <label class="col-xs-4 control-label text-left">表册号</label>
        <input class="col-xs-8" v-model="model.f_meterbook_id" placeholder="请输入表册号">
      </div>
      <div class="row app-input">
        <label class="col-xs-4 control-label text-left">用户编号</label>
        <input class="col-xs-8" v-model="model.f_userinfo_id" placeholder="请输入用户编号">
      </div>
      <div class="row app-input">
        <label class="col-xs-4 control-label text-left">用户姓名</label>
        <input class="col-xs-8" v-model="model.f_user_name" placeholder="请输入用户姓名">
      </div>
      <div class="row app-input">
        <label class="col-xs-4 control-label text-left">用户地址</label>
        <input class="col-xs-8" v-model="model.f_address" placeholder="请输入用户地址">
      </div>
      <div class="row app-input">
        <label class="col-xs-4 control-label text-left">开始时间</label>
        <datepicker
          :value.sync="model.f_start_date"
          :disabled-days-of-week="[]"
          :format="'yyyy-MM-dd'"
          :show-rest-button="reset"
          v-model="model.f_start_date"
          condition="f_checkdate >= '{}'">
        </datepicker>
      </div>
      <div class="row app-input">
        <label class="col-xs-4 control-label text-left">结束时间</label>
        <datepicker
          :value.sync="model.f_end_date"
          :disabled-days-of-week="[]"
          :format="'yyyy-MM-dd'"
          :show-rest-button="reset"
          v-model="model.f_end_date"
          condition="f_checkdate >= '{}'">
        </datepicker>
      </div>
      <div class="row app-input">
        <label class="col-xs-4 control-label text-left">抄表状态</label>
        <input class="col-xs-8" v-model="model.f_meter_state" placeholder="请输入抄表状态">
      </div>
      <div class="row app-input">
        <label class="col-xs-4 control-label text-left">收费状态</label>
        <input class="col-xs-8" v-model="model.f_whether_pay" placeholder="请输入收费状态">
      </div>
      <div class="app-btn">
      <button type="button" name="button" class="btn btn-primary"  @click="this.$back()">
        <span  class="glyphicon glyphicon-remove-circle" style="margin-right: 15px;"></span>返回
      </button>
      <button type="button" name="button" class="btn btn-primary"  @click="search()">
        <span  class="glyphicon glyphicon-zoom-in" style="margin-right: 15px;"></span>查询
      </button>
    </div>

    <div v-for='row in user' class="app-list">
      <div class="row" style="color: #00B9F1;">
        <span class="col-xs-3">户号：</span><span class="col-xs-3">{{row.f_userinfo_id}}</span>
        <span class="col-xs-3">姓名：</span><span class="col-xs-3">{{row.f_user_name}}</span>
      </div>
      <div class="row">
        <span class="col-xs-3">表编号：</span><span class="col-xs-3">{{row.f_user_id}}</span>
        <span class="col-xs-3">用户电话：</span><span class="col-xs-3">{{row.f_user_phone}}</span>
      </div>
      <div class="row">
        <span class="col-xs-4">用户地址：</span><span class="col-xs-8">{{row.f_address}}</span>
      </div>
      <div class="row">
        <span class="col-xs-4">抄表时间：</span><span class="col-xs-8">{{row.f_hand_date}}</span>
      </div>
      <div class="row">
        <span class="col-xs-3">缴费时间：</span><span class="col-xs-3">{{row.f_delivery_date}}</span>
        <span class="col-xs-3">缴费费用：</span><span class="col-xs-3">{{row.f_collection}}</span>
      </div>
      <div class="row">
        <span class="col-xs-4">抄表状态：</span><span class="col-xs-8">{{row.f_meter_state}}</span>
      </div>
      <div class="row">
        <span class="col-xs-3">缴费状态：</span><span class="col-xs-3">{{row.f_whether_pay}}</span>
        <span class="col-xs-3 col-xs-offset-3"  @click="oldprint(row)"><button class="btn btn-link">票据补打</button></span>
      </div>
    </div>
  </div>
</template>

<script>
import * as Util from '../Util'
import appData from '../../../src/components/appData'
import config from '../../../src/components/config'
import Vue from 'vue'
import co from 'co'
let usersearch = function * (self) {
  // config.resultUrl +
  let condition = `1=1 and s.f_charge_state = '有效' and h.f_inputtor = '${appData.loginUser.logininfo[0].f_bieming}'`
  for (var key in self.model) {
    console.log(key);
    if (self.model[key] !== '' ) {
      if (key === 'f_start_date' || key === 'f_end_date' || key === 'f_meter_state' || key === 'f_whether_pay'  ) {
        if (key === 'f_start_date') {
            condition  += ` and f_delivery_date >= '${self.model['f_start_date']} 00:00:00' `
        } else if (key === 'f_end_date') {
          condition  += ` and f_delivery_date <= '${self.model['f_end_date']} 23:59:59'`
        } else if (key === 'f_meter_state') {
          condition  += ` and h.f_meter_state like '%${self.model['f_meter_state']}%'`
        } else if (key === 'f_whether_pay') {
          condition  += ` and h.f_whether_pay = '${self.model['f_whether_pay']}'`
        }

      } else {
        condition  = condition + ` and s.${key} like '%${self.model[key]}%'`
      }
      console.log(condition);
    }
  }
  yield self.$post(config.resultUrl +'rs/sql/handpay', {data: {condition:condition}},
  // yield self.$post('rs/sql/handpay', {data: {condition:condition}},
   {resolveMsg: null, rejectMsg: null})
  .then ((res)=> {
    self.user = res.data
  })
  .catch ((res)=> {
    self.$showMessage('获取用户数据失败，请查看你输入的查询信息')
  })
}
// 打印
let pay = function * (self,data,row) {
        //获取详细单价
        let stairprice_id = `(`
        for (var t = 0; t < data.length; t++) {
          if (t < data.length-1) {
            stairprice_id = stairprice_id + `${data[t].sid},`
          } else if (t === data.length-1 ) {
            stairprice_id = stairprice_id + `${data[t].sid}`
          }
        }
        stairprice_id += `)`
        let condi = `1=1 and f_stairprice_id != '' and f_stairprice_id in ${stairprice_id}`
        yield self.$post(config.resultUrl +'rs/sql/singleTable_Close', {data:{condition: condi,items: `SUM(f_price) price,f_stairprice_id`,tablename: 't_detailprice',orderitem:'f_stairprice_id',groupitem: 'f_stairprice_id'}},
        // self.$post('rs/sql/singleTable_Close', {data:{condition: condi,items: `SUM(f_price) price,f_stairprice_id`,tablename: 't_detailprice',orderitem:'f_stairprice_id',groupitem: 'f_stairprice_id'}},
        {resolveMsg: null, rejectMsg: null})
        .then((res)=>{
          //组织打印数据
          //循环出多套水价的类别和水价，水费和水量
          // p 水价，w 水量，f 水费
          //json 对象 d,ds
          let p = 0
          let w = 0
          let f = 0
          let d = {}
          let ds=[]
          let owe   = self.$post(config.resultUrl +'rs/sql/handowefee', {data:{condition: `h.f_user_id='${row.f_user_id}' and h.f_userinfo_id = '${row.f_userinfo_id}' and s.f_delivery_date = '${row.f_delivery_date}' `}},
           // self.$post('rs/sql/handowefee', {data:{condition: `h.f_user_id='${row.f_user_id}' and h.f_userinfo_id = '${row.f_userinfo_id}' and s.f_delivery_date = '${row.f_delivery_date}' `}},
          {resolveMsg: null, rejectMsg: null})
          .then((oweres)=>{
            for (var i = 0; i < data.length; i++) {
              console.log(i)
              console.log(data[i].sid)
              p=0
              w=0
              f=0
              d={}
              //水价
              console.log('开始相加单价');
              for (var j = 0; j < res.data.length; j++) {
                console.log(j)
                console.log(res.data[j].f_stairprice_id)

                if (data[i].sid === res.data[j].f_stairprice_id) {
                  console.log(res.data[j].price)
                  p = res.data[j].price
                }
              }
              w = oweres.data[0].f_oughtamount * data[i].f_ratio//水量
              f = w*p//水费
              d.type= data[i].f_price_name
              d.price = p
              d.w = w
              d.f = f.toFixed(2)
              ds.push(d)
              console.log(ds)
              }
            let das = ''
            for (var g = 0; g < ds.length; g++) {
              for (var key in ds[g]) {
                if (key === 'type') {
                  das = das + `类别: ${ds[g].type}  `
                } else if (key === 'price') {
                  das = das + `水价: ${ds[g].price}\n`
                } else if (key === 'w') {
                  das = das + `水量${ds[g].w}吨  `
                } else if (key === 'f') {
                  das = das + `水费${ds[g].f}元\n`
                }
              }
            }
            console.log(das);

            let qf = ''
            for (var k = 1; k < oweres.data.length; k++) {
                  qf = qf + `欠费时间 ${oweres.data[k].f_hand_date}\n`+
                  `欠水量 ${oweres.data[k].f_oughtamount}吨 ${oweres.data[k].f_oughtfee} 元\n`
            }
            console.log(qf)
            //${Util.toStandardDateString()}

            //获取上次抄表时间
            let con = `1=1 and  id =(select max(id) from t_handplan where f_meter_state = '已抄表' and f_whether_pay = '是' and f_user_id = '${row.f_user_id}'
			and f_input_date != (select MAX(f_input_date)from t_handplan where f_meter_state = '已抄表' and f_whether_pay = '是' and f_user_id = '${row.f_user_id}'))`
            self.$post(config.resultUrl +'rs/sql/singleTable_OrderBy', {data:{condition: con ,items: 'f_hand_date',tablename: 't_handplan',orderitem:'f_hand_date'}},
              // this.$post('rs/sql/singleTable_OrderBy', {data:{condition: con ,items: 'f_hand_date',tablename: 't_handplan',orderitem:'f_hand_date'}},
            {resolveMsg: null, rejectMsg: null})
            .then((handres)=>{
              self.hand = handres.data
              let lasthanddate = handres.data.length>0?handres.data[0].f_hand_date:row.f_delivery_date
              self.printdata  = `      博能燃气有限公司\n`+
                                `          水费收费单\n`+
                                `   用户编号:${row.f_userinfo_id}抄表员:${row.f_inputtor}\n\n` +
                                `用户名称：${row.f_user_name}\n`+
                                `用户地址：${row.f_address}\n`+
                                `上期抄表日：${lasthanddate}\n` +
                                `本期抄表日：${row.f_delivery_date}\n`+
                                `上期底数：${oweres.data[0].f_last_tablebase}\n`+
                                `本期底数：${oweres.data[0].f_tablebase}\n`+
                                `本期水量：${oweres.data[0].f_oughtamount}\n`+
                                `本期水费：${oweres.data[0].f_oughtfee}\n`+
                                 das+
                                 `********************************\n`+
                                 qf +
                                 `********************************\n`+
                                 `应收： ${row.f_collection}                                       `
              console.log(self.printdata)
              self.print()
            })
            .catch((handret)=>{
              this.$showMessage('获取上次抄表日期失败')
            })

          })
          .catch((oweret)=>{
            self.$showMessage('获取抄表收费信息,检查网络和和设备，从新打印')
          })

        })
        .catch((ret)=>{
          self.$showMessage('获取具体水价信息失败,检查网络和和设备，从新打印')
        })

}
export default {
  title:'缴费明细',
  data () {
    return {
      model: {
        f_meterbook_id:'',
        f_userinfo_id: '',
        f_user_name: '',
        f_start_date: Util.toStandardDateString(),
        f_end_date: Util.toStandardDateString(),
        f_whether_pay: '是',
        f_meter_state: '已抄表'
      },
      user: [],
      printdata: '',
      hand: [],
    }
  },
  methods: {
    print () {
      let result =  HostApp.print(this.printdata)
      if (result.code === 200) {
        this.$showMessage('票据打印成功')
      } else if (result.code === 501) {
        this.$showMessage('票据打印失败，蓝牙连接不可用，检查蓝牙')
      } else {
        this.$showMessage('票据打印失败，蓝牙连接不可用，检查蓝牙')
      }

    },
    //所需数据查询
    search () {
      let gen = usersearch(this)
      return co(gen)
    },
    //票据补打页面
    oldprint (row)  {
      this.$showMessage('是否进行票据补打' ,['confirm','cancel'])
      .then((res)=>{
        if (res === 'confirm') {
          //获取价格比率和描述
          let condition = `1=1 and u.f_user_id= '${row.f_user_id}' and u.f_state = 1 and u.f_price_id = s.f_userprice_id and s.f_state = '有效'`
          let items = `u.*,s.id sid`
          let tablename = `t_userprice u, t_stairprice s`
          this.$post(config.resultUrl +'rs/sql/singleTable_OrderBy', {data:{condition: condition,items: items,tablename: tablename,orderitem:'u.f_user_id'}},
          // this.$post('rs/sql/singleTable_OrderBy', {data:{condition: condition,items: items,tablename: tablename,orderitem:'u.f_user_id'}},
          {resolveMsg: null, rejectMsg: null})
          .then((res)=>{
            let gen = pay(this, res.data,row)
            return co(gen)
          })
          .catch((ret)=>{
            this.$showMessage('获取水价信息失败')
          })
        }
      })
    }
  }
}
</script>
